package com.xiashitech.agent;

import com.xiashitech.agent.boot.LoadClassHelper;
import com.xiashitech.agent.cache.classloader.ClassLoaderCache;
import com.xiashitech.agent.config.EnvConfig;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.instrumentation.base.launch.LaunchTelemetry;
import com.xiashitech.agent.instrumentation.log.XSLevel;
import com.xiashitech.agent.utils.CacheUtil;
import com.xiashitech.agent.utils.LaunchPathParseUtil;
import com.xiashitech.agent.utils.StartupUtil;
import com.xiashitech.interfaces.agent.constants.AgentStatus;
import io.opentelemetry.javaagent.bootstrap.internal.InstrumentationConfig;

import java.lang.instrument.Instrumentation;
import java.util.jar.JarFile;
import java.util.logging.Logger;

public class Agent {
    private static final Logger logger = Logger.getLogger(Agent.class.getName());
    private static final String agentPath = LaunchPathParseUtil.getAgentPackage();
    public static void main(String[] args) {
    }

    /**
     * @param agentArgs,格式:key@value#....
     * @param inst
     */
    public static void premain(String agentArgs, Instrumentation inst) {
        try {
            EnvConfig.configFromEnv();
            LaunchTelemetry.launch(agentArgs,inst,agentPath);
            LoadClassHelper.init(agentPath);
            ClassLoaderCache.setLaunchClassLoader(Agent.class.getClassLoader());
            StartupUtil.premainBefore(agentArgs);
            CacheUtil.syncAgentStatus(AgentStatus.RUNNING);
            StartupUtil.setDiagnosisClassLoader(agentPath);
            StartupUtil.premainAfter(agentArgs);
            StartupUtil.initLocalDBAndRegPushChanel();
            if(InstrumentationConfig.get().getBoolean("xs.debug",false)) {
                logger.log(XSLevel.DEBUG, "The Agent for safe instrumentation has been started!");
            }
            StartupUtil.onLineDiagnosis(inst, StartConfig.getParamValueFromKey(StartConfig.agentService), StartConfig.getParamValueFromKey(StartConfig.systemId), InstrumentationConfig.get().getString("otel.service.name"));
        } catch (Exception e) {
            StartConfig.throwableStackPrinter(e);
        }
    }

    public static void agentmain(String agentArgs, Instrumentation inst) {
        //todo:后续根据场景需要添加
    }
}